const app = getApp();
const { mfutil, HttpRequest, globalData, UserAccess, HTTPOuid } = getApp();
const memberPlugin = requirePlugin("cemMember");
Page({
  data: {
    router: '/pages/index/index',
    expend: false,
    loadingActive: false
  },
  onLoad(query) {

    my.hideShareMenu({
      success() {
      },
      fail() {
      },
    });
    this.getSystemInfoPage();
    mfutil.onLoad(query);
  },

  async onShow() {
    mfutil.authorize((res) => {
      app.globalData.accessToken = res.accessToken.accessToken;
      my.getAuthUserInfo({
        success: async (userInfo) => {
          console.log(userInfo);

          globalData.user_nick = userInfo.nickName || "";
          console.log("444444444444444444444444444444")
          await this.OUID()
                    console.log("55555555555555555555555555555555")
          await this.Member()
                          console.log("666666666666666666666666666")
        },
        fail: () => {
          // mfutil.launchErrPage(53001)
        }
      })
    });
  },
  async OUID() {
    console.log("111111111111111-------------");

    this.setData({
      loadingActive: true
    })
    // taobao-service-ouid/api/v2.1/taobao/vans/getOuid
    // https://engageapi-stg.vans.com.cn
    let path = 'taobao-service-ouid/api/v2.1/taobao/vans/getOuid';
    this.setData({
      loadingActive: true
    })
    let result = await HTTPOuid(path, 'GET', {}, {})
    console.log(result);

    this.setData({
      loadingActive: false
    })
    console.log(result);
    globalData.ouid = result.ouid;
  },
  Member() {
    memberPlugin.checkMember({
      //sellerId为可选参数，不填则为当前小程序Owner用户ID
      // sellerId: '',
      success: (v) => {
        if (v.data && v.data.isMember !== 'false') {
          this.isMemberCLM()
        } else {
          this.openMember()
        }
      },
      fail(v) {
        mfutil.launchErrPage(53001)
        console.log('失败')
      }
    });
  },
  async openMember(event) {
    this.setData({ expend: true, })
  },
  async onClose(event) {
    this.setData({ expend: false, })
    this.Member()
  },
  async onAuthSuccess(res) {
    this.setData({ expend: false, })
    this.Member()
    /**
        * 用户行为记录埋点
        */
    let options = {
      grade: '',
      name: '用户入会成功',
      address: 'onAuthSuccess',
    }
    let track = UserAccess(options)
  },
  async onAuthFail(res) {
    this.setData({ expend: false, })
    this.Member()
  },
  getLocation() {
    my.getLocation({
      success(res) {
        app.globalData.Location.longitude = res.longitude;
        app.globalData.Location.latitude = res.latitude;
      },
      fail() {
        my.alert({ title: '定位失败' });
      },
    })
  },
  onLaunch() {

  },
  authorizeFn() {

  },
  async onReady() {
    // 页面加载完成
    mfutil.onReady();
  },

  jump() {
    my.redirectTo({
      url: '/pages/index2/index2'
    })
  },
  jump2() {
    my.redirectTo({
      url: '/pages/editorAnalysis/editorAnalysis'
    })
  },
  async test() {
    let time = new Date().getTime();
    let res = await mfutil.cloud.ajax({
      name: 'cache', exts: {
        cacheType: 1,
        cacheTime: 600
      },
    });
    my.alert({ content: `缓存时间:10分钟,请求:${res}时间:${new Date().getTime() - time}` })
  },
  async test1() {
    let time = new Date().getTime();
    let res = await mfutil.cloud.ajax({
      name: 'cache'
    });
    my.alert({ content: `请求:${res}时间:${new Date().getTime() - time}` })
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },
  imgOl(e) {
  },
  getSystemInfoPage() {
    console.log("111111111111111111111111111")
    my.getSystemInfo({
      success: async (res) => {
        const rate = res.screenHeight / res.screenWidth;
        let limit = res.windowHeight == res.screenHeight ? 1.8 : 1.779; // 临界判断值
        let scrollHright = res.statusBarHeight;
        app.globalData.scrollHright = scrollHright;
        app.globalData.SystemInfo = res
        app.globalData.rpx = res.windowWidth / 750;
        app.globalData.screenHeight = res.windowHeight * res.pixelRatio;
        this.setData({
          rate,
          limit
        })
        app.globalData.rate = rate;
        app.globalData.limit = limit;
        // this.Member()
        /**
    * 用户行为记录埋点
    */
   console.log("2222222222222222222222222222222222222222222222222")
        let params = app.globalData.params;
        let channel = app.globalData.channel;
        let options = {
          grade: '',
          name: '进入小程序',
          address: '/pages/index/index',
          String4: params ? `params=${params.join(',')}${channel ? '&channel=' + channel : ''}` : ''
        }
        let track = UserAccess(options)
           console.log("333333333333333333333333333333333333333333333333")
        console.log(track)
      },
      fail: () => {
        mfutil.launchErrPage(53001)
      }
    })
  },
  async isMemberCLM() {
    let { rate, limit } = this.data;
    let bodyObj1 = {
      "param": globalData.ouid,
      "type": 3
    }
    let path1 = `/vans-family/api/v2.1/project/vansFamily/clm/forward/sendjson/get?url=/v1/member/api/tmall/query`;
    this.setData({
      loadingActive: true
    })
    let res1 = await HttpRequest(path1, 'POST', '', bodyObj1)
    this.setData({
      loadingActive: false
    })
    if (res1.data.resultCode == '0' && res1.data.data.status == '1') {
      // res1.data.data.fullName = res1.data.data.fullName!=''? res1.data.data.fullName: '会员';
      globalData.userInfo = res1.data.data;
      console.log('000000000', '会员')
      my.switchTab({
        url: `/pages/integral-page/integral-page`
      })
    } else if (res1.data.resultCode == '0' && res1.data.data.status == '0') {
      // 如果大于，全面屏,否则，非全面平,非会员进入注册页
      console.log('11111111', '非会员')
      if (rate > limit) {
        my.reLaunch({
          url: `/pages/index1624/index1624`
        })
      } else {
        my.reLaunch({
          url: `/pages/index1334/index1334`
        })
      }
    } else if (memberres.data.data.status == '2') {      // 查询结果其他渠道已绑定会员，调用会员入会接口，成功后进入dashboard页面      2
      console.log('@@@@@@@@@@@@@@@@@@111111111111');
      let birthYear = new Date(memberres.data.data.birthDate).getFullYear();
      let birthMonth = new Date(memberres.data.data.birthDate).getMonth() + 1;
      let birthDay = new Date(memberres.data.data.birthDate).getDate();
      let registerObj = {
        "mobilePhone": memberres.data.data.mobilePhone,
        "source": 100000020,
        "subSource": 100000501,
        "fullName": memberres.data.data.fullName,
        "genderCode": memberres.data.data.genderCode,
        "birthYear": birthYear,
        "birthMonth": birthMonth,
        "birthDay": birthDay,
        "thirdType": 1,
        "thirdPartyId": globalData.ouid,
        "storeCode": "TMALL"
      }
      console.log(registerObj, 'registerObjregisterObjregisterObjregisterObj')
      let registerpath = `/vans-family/api/v2.1/project/vansFamily/clm/forward?url=/v1/member/api/tmall/register`;
      let registerres = await HttpRequest(registerpath, 'POST', '', registerObj);
      if (registerres.data.resultCode == '0') {
        my.redirectTo({
          url: '/pages/integral-page/integral-page'
        });
      }
    } else {
      mfutil.launchErrPage(53001)

    }
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: 'My App',
      desc: 'My App description',
      path: 'pages/index/index',
    };
  },

});
